#!/usr/bin/ruby

require 'cgi'
require "sqlite3"
require 'pp'

# FIXME: move some functionality to join

#require File.dirname(__FILE__) + "/shared.rb"
require '/opt/radio-monitor/shared.rb'
require JOIN_RB
require PLOT_RB

FORM_CGI_VARS = ["start_year", "start_month", "start_day", \
"start_hour", "start_min", "dur_hour", "dur_min"]
MSG_PAT = "::message::"
NO_DATA_ERR = 'No data available for the given range.'
BIG_REC_ERR = 'Requested recording is too large to serve.'

MAX_REC_LEN = 60*60*12

def get_times(cgi)
    start_year  = cgi["start_year"][0].to_i
    start_month = cgi["start_month"][0].to_i
    start_day   = cgi["start_day"][0].to_i
    start_hour  = cgi["start_hour"][0].to_i
    start_min   = cgi["start_min"][0].to_i
    dur_hour    = cgi["dur_hour"][0].to_i
    dur_min     = cgi["dur_min"][0].to_i

    start_t = Time.mktime(\
        start_year, start_month, start_day, start_hour, start_min).to_i
    end_t = start_t + dur_hour*60*60 + dur_min*60
    
    return start_t.to_i, end_t.to_i
end

def print_form(cgi, message='')
    puts "Content-type: text/html \n\n"
    puts "<!--"
    pp cgi
    puts "-->"
    puts File.new(INDEX_HTML, 'r').read.gsub(MSG_PAT, message)
end

def get_entries(start_t, end_t)
    db = SQLite3::Database.new(DB_FILE)
    cmd = "SELECT * FROM Recordings \
            WHERE #{start_t}    <= #{START_T_COL} \
            AND   #{END_T_COL}  <= #{end_t};"
    return db.execute(cmd)
end

def main
    cgi = CGI.new.params
    
    if FORM_CGI_VARS.map {|v| cgi.member?(v)}.member?(false)
        print_form(cgi)
    else
        start_t, end_t = get_times(cgi)
        entries = get_entries(start_t, end_t)
        if entries.length == 0
            print_form(cgi, NO_DATA_ERR) 
        elsif cgi.member?("plot") and cgi["plot"][0] == "true"
            entries.map! {|x| [x[START_T_DBI].to_i, x[END_T_DBI].to_i, 
                    x[ACT_LEN_DBI].to_i]}.sort! {|x,y| x[0]<=>y[0]}
            plot(entries)
        elsif end_t - start_t < MAX_REC_LEN
            entries.map! {|x| [x[START_T_DBI].to_i, x[FNAME_DBI]]}\
                    .sort! {|x,y| x[0]<=>y[0]}
            join_recs(entries)
        else
            print_form(cgi, BIG_REC_ERR) 
        end
    end
end

if __FILE__ == $0
    main
end

